package com.nf.health.app.chatservice.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;

import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMGroup;
import com.hyphenate.easeui.EaseConstant;
import com.hyphenate.exceptions.HyphenateException;
import com.nf.health.app.Constants;
import com.nf.health.app.R;
import com.nf.health.app.activity.global.BaseActivity;
import com.nf.health.app.db.DbManager;
import com.nf.health.app.inquiry.docdetail.DocDetailActivity;
import com.nf.health.app.utils.ActivityUtils;
import com.nf.health.app.utils.ViewUtil;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * Created by Jason on 2016/4/28.
 */
public class GroupChatSettingActivity extends BaseActivity {
    @Bind(R.id.bt_exsit_group)
    Button bt_exsit_group;
    @Bind(R.id.tl_sound_tb)
    ToggleButton tl_sound_tb;
    @Bind(R.id.tv_griup_num)
    TextView tv_griup_num;
    @Bind(R.id.rl_modify_infor)
    RelativeLayout rl_modify_infor;
    @Bind(R.id.rl_group_to)
    RelativeLayout rl_group_to;
    @Bind(R.id.tv_groupoName)
    TextView tv_groupoName;
    private String toChatUsername;
    private String is_forbit_other_talk;
    private String doctorId = "";
    private String doctorName = "";
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setTitleBar(R.layout.titlebar_base);
        setContent(R.layout.activity_group_setting);
        ButterKnife.bind(this);
        ViewUtil.setText(this, R.id.titlebar_title_tv, "群设置");
        bt_exsit_group.setOnClickListener(this);
        rl_modify_infor.setOnClickListener(this);
        rl_group_to.setOnClickListener(this);
        //从关注的医生过来的界面 Is
        toChatUsername = getIntent().getExtras().getString(EaseConstant.EXTRA_USER_ID);
        new Thread(new Runnable() {
            @Override
            public void run() {
                //根据群聊ID从本地获取群聊基本信息
                //根据群组ID从本地获取群组基本信息
                try {
                    EMClient.getInstance().groupManager().getGroupFromServer(toChatUsername);
                    //根据群组ID从服务器获取群组基本信息
                    EMGroup group = EMClient.getInstance().groupManager().getGroup(toChatUsername);
                     int i = EMClient.getInstance().groupManager().getGroup(toChatUsername).getAffiliationsCount();
                    Message msg = handler.obtainMessage();
                    msg.what = 1;
                    msg.obj = i;
                    handler.sendMessage(msg);

                } catch (HyphenateException e) {
                    e.printStackTrace();
                }
            }
        }).start();
        EMGroup group = EMClient.getInstance().groupManager().getGroup(toChatUsername);
        doctorName = DbManager.getInstance().getOneGroupManager(group.getOwner());
        int i = group.getAffiliationsCount();
        doctorId = group.getOwner();
        ViewUtil.setText(GroupChatSettingActivity.this,R.id.tv_griup_num,String.valueOf(i)+"人");
        if(TextUtils.isEmpty(group.getGroupName())){
            tv_groupoName.setText("未知");
        }else{
            tv_groupoName.setText(""+doctorName);//group.getMembers().get(0)
        }
        if (EMClient.getInstance().groupManager().getGroup(toChatUsername).isMsgBlocked()) {
            tl_sound_tb.setChecked(true);
            tl_sound_tb.setTag(Constants.OPEN_FORBIT_HUANXIN_MSG);
        } else {
            tl_sound_tb.setChecked(false);
            tl_sound_tb.setTag(Constants.CLOASE_FORBIT_HUANXIN_MSG);
        }

        tl_sound_tb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(CompoundButton arg0, boolean arg1) {
                Integer tag = (Integer) tl_sound_tb.getTag();
                String st8 = getResources().getString(R.string.group_is_blocked);
                final String st9 = getResources().getString(R.string.group_of_shielding);
                if (!EMClient.getInstance().groupManager().getGroup(toChatUsername).isMsgBlocked()) {//屏蔽群消息
                    showLoading();//getResources().getString(R.string.Is_unblock)
                    new Thread(new Runnable() {
                        public void run() {
                            try {
                                EMClient.getInstance().groupManager().blockGroupMessage(toChatUsername);
                                runOnUiThread(new Runnable() {
                                    public void run() {
                                        hideLoading();
                                        //showToast("屏蔽群消息");
                                        tl_sound_tb.setChecked(true);
                                    }
                                });
                            } catch (Exception e) {
                                e.printStackTrace();
                                runOnUiThread(new Runnable() {
                                    public void run() {
                                        showToast(st9);
                                        hideLoading();
                                        tl_sound_tb.setChecked(false);
                                    }
                                });
                            }

                        }
                    }).start();
                } else {//解除 屏蔽群消息
                    showLoading(getResources().getString(R.string.Is_unblock));
                    new Thread(new Runnable() {
                        public void run() {
                            try {
                                //EMGroupManager.getInstance().unblockGroupMessage(groupId);
                                EMClient.getInstance().groupManager().unblockGroupMessage(toChatUsername);
                                runOnUiThread(new Runnable() {
                                    public void run() {
                                        hideLoading();
                                       // showToast("已开启");
                                        tl_sound_tb.setChecked(false);
                                    }
                                });
                            } catch (Exception e) {
                                e.printStackTrace();
                                runOnUiThread(new Runnable() {
                                    public void run() {
                                        hideLoading();
                                        tl_sound_tb.setChecked(true);
                                        showToast(getResources().getString(R.string.remove_group_of));
                                    }
                                });

                            }
                        }
                    }).start();
                }

            }
        });
    }


    @Override
    public void onClick(View v) {
        super.onClick(v);

        switch (v.getId()) {
            case R.id.bt_exsit_group://退出该群
//                chatBundle.putString(Constants.EXTRA_USER_ID, toChatUsername);
//                chatBundle.putInt(Constants.EXTRA_CHAT_TYPE, Constants.CHATTYPE_GROUP);
//                //ActivityUtil.showActivity(ChatActivity.this, GroupDetailsActivity.class, chatBundle);
//                ActivityUtil.showActivityForResult(ChatActivity.this, GroupDetailsActivity.class, chatBundle,Constants.CODE_ENFRY_SETTINGS);
                exitGrop(toChatUsername);
                break;
            case R.id.rl_group_to:
                if(TextUtils.isEmpty(doctorId)){
                        return  ;
                }
                Bundle bundle = new Bundle();
                bundle.putString(DocDetailActivity.DOCTORID,doctorId);
                ActivityUtils.showActivity(GroupChatSettingActivity.this, DocDetailActivity.class, bundle);
                break;
        }
    }
    /**
     * 退出群组
     *
     * @param groupId
     */
    private void exitGrop(final String groupId) {
        showLoading();
        String st1 = getResources().getString(R.string.Exit_the_group_chat_failure);
        new Thread(new Runnable() {
            public void run() {
                try {
                    EMClient.getInstance().groupManager().leaveGroup(groupId);
                    runOnUiThread(new Runnable() {
                        public void run() {

                            setResult(RESULT_OK);
                            finish();
                            sendBroadcast(new Intent(Constants.EXIST_SPECIAL_SIGN_FORBIT_GROUP_ID_REFRESH));
                            sendBroadcast(new Intent(Constants.CHAT_CLOSE));
                            hideLoading();
                        }
                    });
                } catch (final Exception e) {
                    runOnUiThread(new Runnable() {
                        public void run() {
                            hideLoading();
                            Toast.makeText(getApplicationContext(), getResources().getString(R.string.Exit_the_group_chat_failure) + " " + e.getMessage(), Toast.LENGTH_LONG).show();
                        }
                    });
                }
            }
        }).start();
    }
    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case 1:
                    int i = (int) msg.obj;
                    ViewUtil.setText(GroupChatSettingActivity.this,R.id.tv_griup_num,String.valueOf(i)+"人");
                    break;
            }
        }
    };

}
